# -*- coding: utf-8 -*-

from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.shortcuts import render_to_response
from django.template import Context
from django.template import RequestContext
from django.template import TemplateDoesNotExist
from models import *
from widgets.forms import *
from widgets.forms import NoteForm

def pokaz(request, wid=None):
    try:
        print wid
        module = Modules.objects.get(module=wid)
        widget = Widget.objects.get(wid=module, owner=request.user)
    except ObjectDoesNotExist:
        raise Http404
	
    if module.module == 'notatki':
        list = Note.objects.filter(widget=widget)
    template_name = 'widgets/%s.html' % module.module
    try:
        return render_to_response(template_name, locals(), context_instance=RequestContext(request))
    except TemplateDoesNotExist:
        pass
    raise Http404

def showNotes(request, wid="note"):
    """
    Could/should be used by AJAX to retrive an notes widget content
    """
    notes = Note.objects.all()

    return render_to_response('widgets/notatki.html', {'list':notes})

def editNote(request, wid="note"):
    """
    Used for AJAX requests for saving a modified note or adding a new one
    """
    print request.POST
    if(request.method == 'POST'):
        note_id = request.POST['element_id'].split("_")[-1]
        print note_id
        module = Modules.objects.get(module=wid)
        widget = Widget.objects.get(wid=module, owner=request.user)
        note = get_object_or_404(Note, pk=note_id, widget=widget)

        note.tresc = request.POST['update_value']
        note.save()
        return HttpResponse(request.POST['update_value'])
    return HttpResponse(request.POST['original_html'])#couldn't save, return previous value

def addNote(request, wid="note"):
    """
    Used for AJAX requests for adding a new one
    """
    if(request.method == 'POST'):
        #TODO: Could be done better by binding with NoteForm?
        form = NotatkaForm(request.POST)
        print request.POST
        if form.is_valid():
            note = Note()
            note.tresc = request.POST['tresc']
            module = Modules.objects.get(module=wid)
            widget = Widget.objects.get(wid=module, owner=request.user)
            note.widget_id = widget.id
            note.save()
            return render_to_response('widgets/notatka.html', {'obj': note}, context_instance=RequestContext(request))#TODO: żeby nie musieć tego ręcznie podawać!!!
        return Http404("Nie zapisano notatki...")
    raise Http404()

def deleteNote(request, note_id):
    """
    Used for AJAX requests for deleting an existing note by it's ID
    """
    if(request.method == 'GET'):#nie wyszczególniać może? głupio GETem kasować w sumie
        note = Note.objects.get(pk=note_id)
        widget = Widget.objects.get(id=note.widget_id, owner=request.user)
        if widget:
            note.delete()
            return HttpResponse("Usunięto notatkę...")
    raise Http404()
